package com.lct.simpleforecast.extensions

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.lct.simpleforecast.R

/**
 * Author：SkySmile
 * Date：2018/7/4
 * Description：对View的扩展
 */

val View.ctx: Context
    get() = context

//value是资源文件中的colorId
var TextView.color: Int
    get() = currentTextColor
    set(value) {
        setTextColor(android.support.v4.content.ContextCompat.getColor(ctx, value))
    }

fun ImageView.loadImgByGlide(imgUrl: String) {
    Glide.with(ctx)
            .load(imgUrl)
            .apply(RequestOptions()
                    .placeholder(R.drawable.img_preview)
                    .error(R.drawable.img_load_error))
            .into(this)
}

fun TextView.setTextWithFormatArgs(stringResourceId: Int, vararg formatArgs: String) {
    this.text = ctx.resources.getString(stringResourceId, *formatArgs)
}

inline fun EditText.afterTextChanged(crossinline afterChanged: (String) -> Unit) {
    addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }

        override fun afterTextChanged(s: Editable?) {
            if (s.toString().isNotBlank()) {
                afterChanged(s.toString())
            }
        }
    })
}

fun View.hideKeyboard(): Boolean {
    try {
        val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE)
                as InputMethodManager
        return inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
    } catch (ignored: RuntimeException) {
    }
    return false
}